import UI_cmp_obj_title from "../../../ui/Main/UI_cmp_obj_title";
import { BaseViewCmp } from "./BaseViewCmp";
import { EObjCmpType } from "../../debug_inject/common/EObjCmpType";
import { BaseCmpData } from "../../debug_inject/common/BaseCmpData";
import { BaseObjDetailData } from "../../debug_inject/common/BaseObjDetailData";
import { NodeTypeHelper } from "../../debug_inject/action/NodeTypeHelper";
import { DebuggerManager } from "../../debugger/DebuggerManager";
import { EventCenter } from "../../../LTGame/Event/EventCenter";
import { EventIDs } from "../../common/EventIds";
import { PropToggle } from "../prop/PropToggle";

export class CmpObjTitle extends BaseViewCmp {

    public ui: UI_cmp_obj_title;

    private _cacheData: BaseObjDetailData;

    private _toggle_active: PropToggle;

    constructor(objId: number) {
        super(EObjCmpType.Base, objId);
        this.ui = UI_cmp_obj_title.createInstance();

        this._toggle_active = new PropToggle(this.ui.m_view_active);
        this._toggle_active.onToggleChanged = Laya.Handler.create(this, this._OnActiveChanged, null, false);

        this.ui.m_view_name.m_btn_submit.onClick(this, this._OnClickSetName);
        this.ui.m_btn_log.onClick(this, this._OnClickLogToConsole);
    }

    _OnDispose() {
        this._toggle_active.Dispose();
    }

    private _OnClickLogToConsole() {
        DebuggerManager.instance.LogToConsole(this.objId);
    }

    private async _OnClickSetName() {
        let result = await DebuggerManager.instance.SetObjName(this.objId, this.ui.m_view_name.m_input_text.text);
        if (!result) {
            this.ui.m_view_name.m_input_text.text = this._cacheData.name;
        } else {
            this._cacheData.name = this.ui.m_view_name.m_input_text.text;
        }
        EventCenter.instance.Send(EventIDs.RefreshObjList, null);
    }

    private async _OnActiveChanged(enable: boolean) {
        this._cacheData.active = enable;
        await DebuggerManager.instance.SetObjActive(this.objId, this._cacheData.active);
        EventCenter.instance.Send(EventIDs.RefreshObjList, null);
    }

    _OnRefresh(data: BaseCmpData) {
        if (this._cacheData != null) {
            let oldJson = JSON.stringify(this._cacheData);
            let newJson = JSON.stringify(data.data);
            if (oldJson == newJson) {
                return;
            }
        }

        this._cacheData = data.data as BaseObjDetailData;
        this._toggle_active.isChecked = this._cacheData.active;
        this.ui.m_view_type.m_display_text.text = NodeTypeHelper.GetTypeName(this._cacheData.type);
        this.ui.m_view_name.m_input_text.text = this._cacheData.name;
    }

}